<template>
  <div class="form-container">
    <h2>注册</h2>
    <form @submit.prevent="handleRegister">
      <!-- 用户名 -->
      <div class="input-group">
        <input
          v-model="form.username"
          placeholder="用户名（3-20个字符，只能包含字母、数字、下划线）"
          required
          @blur="validateUsername"
          :class="{ error: errors.username }"
        />
        <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
      </div>

      <!-- 密码 -->
      <div class="input-group">
        <input
          v-model="form.password"
          type="password"
          placeholder="密码（6-20个字符）"
          required
          @blur="validatePassword"
          :class="{ error: errors.password }"
        />
        <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
      </div>

      <!-- 确认密码 -->
      <div class="input-group">
        <input
          v-model="form.confirmPassword"
          type="password"
          placeholder="确认密码（必须与密码一致）"
          required
          @blur="validateConfirmPassword"
          :class="{ error: errors.confirmPassword }"
        />
        <span v-if="errors.confirmPassword" class="error-message">{{
          errors.confirmPassword
        }}</span>
      </div>

      <!-- 真实姓名 -->
      <div class="input-group">
        <input
          v-model="form.realName"
          placeholder="真实姓名（不超过50个字符）"
          required
          @blur="validateRealName"
          :class="{ error: errors.realName }"
        />
        <span v-if="errors.realName" class="error-message">{{ errors.realName }}</span>
      </div>

      <!-- 身份证号 -->
      <div class="input-group">
        <input
          v-model="form.idCard"
          placeholder="身份证号（18位有效身份证号码）"
          required
          @blur="validateIdCard"
          :class="{ error: errors.idCard }"
        />
        <span v-if="errors.idCard" class="error-message">{{ errors.idCard }}</span>
      </div>

      <!-- 手机号 -->
      <div class="input-group">
        <input
          v-model="form.phone"
          placeholder="手机号（11位，以1开头，第二位3-9）"
          required
          @blur="validatePhone"
          :class="{ error: errors.phone }"
        />
        <span v-if="errors.phone" class="error-message">{{ errors.phone }}</span>
      </div>

      <!-- 用户类型 -->
      <div class="input-group">
        <select
          v-model="form.userType"
          required
          @change="validateUserType"
          :class="{ error: errors.userType }"
        >
          <option disabled value="">请选择用户类型</option>
          <option value="0">普通用户</option>
          <option value="1">学生</option>
          <option value="2">军人等特殊群体</option>
        </select>
        <span v-if="errors.userType" class="error-message">{{ errors.userType }}</span>
      </div>

      <button type="submit" :disabled="!isFormValid">注册</button>
    </form>
    <p>已有账号？<router-link to="/login">登录</router-link></p>
  </div>
</template>

<script setup lang="ts">
import { reactive, computed } from 'vue'
import api from '@/utils/api'
import { useRouter } from 'vue-router'

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  idCard: '',
  phone: '',
  userType: '',
})

const errors = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  idCard: '',
  phone: '',
  userType: '',
})

const router = useRouter()

// 验证函数
function validateUsername() {
  if (!form.username) {
    errors.username = '用户名不能为空'
    return false
  }
  if (form.username.length < 3 || form.username.length > 20) {
    errors.username = '用户名长度必须在3-20个字符之间'
    return false
  }
  if (!/^[a-zA-Z0-9_]+$/.test(form.username)) {
    errors.username = '用户名只能包含字母、数字和下划线'
    return false
  }
  errors.username = ''
  return true
}

function validatePassword() {
  if (!form.password) {
    errors.password = '密码不能为空'
    return false
  }
  if (form.password.length < 6 || form.password.length > 20) {
    errors.password = '密码长度必须在6-20个字符之间'
    return false
  }
  errors.password = ''
  return true
}

function validateConfirmPassword() {
  if (!form.confirmPassword) {
    errors.confirmPassword = '确认密码不能为空'
    return false
  }
  if (form.password !== form.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
    return false
  }
  errors.confirmPassword = ''
  return true
}

function validateRealName() {
  if (!form.realName) {
    errors.realName = '真实姓名不能为空'
    return false
  }
  if (form.realName.length > 50) {
    errors.realName = '真实姓名长度不能超过50个字符'
    return false
  }
  errors.realName = ''
  return true
}

function validateIdCard() {
  if (!form.idCard) {
    errors.idCard = '身份证号不能为空'
    return false
  }
  const idCardPattern =
    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
  if (!idCardPattern.test(form.idCard)) {
    errors.idCard = '身份证号格式不正确'
    return false
  }
  errors.idCard = ''
  return true
}

function validatePhone() {
  if (!form.phone) {
    errors.phone = '手机号不能为空'
    return false
  }
  const phonePattern = /^1[3-9]\d{9}$/
  if (!phonePattern.test(form.phone)) {
    errors.phone = '手机号格式不正确'
    return false
  }
  errors.phone = ''
  return true
}

function validateUserType() {
  if (!form.userType) {
    errors.userType = '请选择用户类型'
    return false
  }
  const userType = parseInt(form.userType)
  if (userType < 0 || userType > 2) {
    errors.userType = '用户类型值不正确'
    return false
  }
  errors.userType = ''
  return true
}

// 表单验证状态
const isFormValid = computed(() => {
  return (
    validateUsername() &&
    validatePassword() &&
    validateConfirmPassword() &&
    validateRealName() &&
    validateIdCard() &&
    validatePhone() &&
    validateUserType()
  )
})

async function handleRegister() {
  console.log('注册信息：', form)

  // 先进行前端验证
  if (!isFormValid.value) {
    alert('请检查输入信息是否正确')
    return
  }

  try {
    const response = await api.post('/api/users/register', {
      username: form.username,
      password: form.password,
      confirmPassword: form.confirmPassword,
      realName: form.realName,
      idCardNumber: form.idCard,
      phoneNumber: form.phone,
      userType: parseInt(form.userType),
    })

    console.log(response.data)
    alert('注册成功！')

    // 获取用户id
    const response_id = await api.get(`/api/users?username=${encodeURIComponent(form.username)}`)

    // 存储用户信息
    localStorage.setItem('username', form.username)
    const userId = response_id.data.userId || response_id.data.id || response_id.data
    localStorage.setItem('userId', userId.toString())

    router.push('/home') // 注册成功跳转
  } catch (error: unknown) {
    console.error(error)

    if (error && typeof error === 'object' && 'response' in error) {
      const errorResponse = error as {
        response: { status: number; data: { message?: string; error?: string } }
      }
      const { status, data } = errorResponse.response
      const msg = data?.message || '未知错误'
      const errorDetail = data?.error || ''

      switch (status) {
        case 503:
          alert('服务暂时不可用，请稍后重试或联系管理员\n\n技术信息：用户服务可能未启动')
          break
        case 502:
          alert('网关连接错误，请稍后重试或联系管理员\n\n技术信息：网关配置可能有问题')
          break
        case 409:
          // 冲突错误，通常是数据重复
          if (msg.includes('用户名') || msg.includes('username')) {
            alert('注册失败：用户名已存在')
          } else if (msg.includes('手机号') || msg.includes('phone')) {
            alert('注册失败：手机号已注册')
          } else if (msg.includes('身份证') || msg.includes('idCard')) {
            alert('注册失败：身份证号已注册')
          } else {
            alert('注册失败：数据冲突 - ' + msg)
          }
          break
        case 400:
          // 参数验证失败
          if (errorDetail) {
            alert(`注册失败：${errorDetail}`)
          } else {
            alert(`注册失败：${msg}`)
          }
          break
        case 500:
          alert('服务器内部错误，请稍后重试或联系管理员')
          break
        default:
          alert('注册失败：' + msg)
      }
    } else if (error && typeof error === 'object' && 'request' in error) {
      alert('网络连接失败，请检查网络连接或联系管理员\n\n技术信息：无法连接到服务器')
    } else {
      alert('请求配置错误：' + (error instanceof Error ? error.message : String(error)))
    }
  }
}
</script>

<style scoped>
body {
  background-color: #f5f5f5;
  margin: 0;
  font-family: Arial, sans-serif;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.form-container {
  background-color: #ffffff;
  max-width: 400px;
  width: 90%;
  padding: 30px;
  border: 1px solid #ddd;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-size: 24px;
}

.input-group {
  margin-bottom: 20px;
  position: relative;
}

input,
select {
  display: block;
  width: 100%;
  padding: 12px;
  box-sizing: border-box;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

input:focus,
select:focus {
  outline: none;
  border-color: #0086f6;
  box-shadow: 0 0 0 3px rgba(0, 134, 246, 0.1);
}

input.error,
select.error {
  border-color: #ff4757;
}

.error-message {
  color: #ff4757;
  font-size: 12px;
  margin-top: 5px;
  display: block;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

button {
  width: 100%;
  padding: 12px;
  background-color: #0086f6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
  transition: background-color 0.3s;
  margin-top: 10px;
}

button:hover:not(:disabled) {
  background-color: #0071e3;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

p {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

a {
  color: #0086f6;
  text-decoration: none;
  font-weight: bold;
}

a:hover {
  text-decoration: underline;
}

/* 占位符样式 */
input::placeholder {
  color: #999;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .form-container {
    padding: 20px;
    margin: 10px;
  }

  h2 {
    font-size: 20px;
  }

  input,
  select {
    padding: 10px;
    font-size: 13px;
  }
}
</style>
